package com.zyl.Ecs.realtime.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zyl.Ecs.common.constant.ConfigConstant;
import com.zyl.Ecs.common.handler.MyBatisPlusFillingHandler;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.realtime.config
 * @ClassName: MyBatisPlusConfig
 * @Description TODO
 * @Author 翟玉龙
 * @Date 2024/12/6-13:44
 */
@Configuration
@RequiredArgsConstructor
@MapperScan(ConfigConstant.MYBATIS_MAPPER_PACKAGE)
public class MyBatisPlusConfig {

    /**
     * 将我们配置的包含多个数据源的动态数据源对象注入进来
     */
    private final DataSource dynamicDataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        /* 写入数据源 */
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        /* 设置映射文件所在路径 */
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(ConfigConstant.MYBATIS_MAPPER_LOCATION));
        org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();
        conf.setDefaultStatementTimeout(100);
        sqlSessionFactoryBean.setConfiguration(conf);
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 将MyBatisPlus中的实体属性处理器注册到Bean容器中
     *
     * @return {@link MetaObjectHandler }
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyBatisPlusFillingHandler();
    }

}
